package com.ljp.order.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ljp.order.entity.Order;
import com.ljp.order.io.Result;
import com.ljp.order.mybatis.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedissonClient redissonClient;

    public Result addOrder(long userId, long id) {
        Order drivingOrder = new Order();
        drivingOrder.setId(id);
        drivingOrder.setStatus(1);
        drivingOrder.setUserId(userId);
        int result = orderMapper.insert(drivingOrder);


        if (result == 1) {

            CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
            correlationData.getFuture().addCallback(new ListenableFutureCallback<CorrelationData.Confirm>() {
                @Override
                public void onFailure(Throwable throwable) {
                    log.info("onFailure ack");
                }

                @Override
                public void onSuccess(CorrelationData.Confirm confirm) {
                    if (confirm.isAck()) {
                        log.info("onSuccess ack,ok");
                    } else {
                        log.info("onSuccess ack,ok");
                    }
                }
            });
            // 添加订单成功，推送一个mq消息
            rabbitTemplate.convertAndSend("amq.direct",
                    "", id, correlationData);
            return Result.ok();
        }
        return Result.fail("订单添加失败！");
    }


    public Result fetchOrder(long id) {

        RLock lock = redissonClient.getLock("driver_order_id_" + id);
        try {
            boolean flag = lock.tryLock(5, 50, TimeUnit.MILLISECONDS);
            if (!flag) {
                return Result.fail("订单已被接收处理！");
            }

            Order drivingOrder = orderMapper.selectById(id);
            // 订单等于1，改成2
            if (drivingOrder.getStatus() == 1) {
                drivingOrder.setStatus(2);
                orderMapper.updateById(drivingOrder);
                return Result.ok();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock != null) {

                lock.unlock();
            }
        }
        return Result.fail("订单已被接收处理！");
    }

    public Result queryOrder(long id) {
        LambdaQueryWrapper<Order> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Order::getId, id);
        Order order = orderMapper.selectOne(lambdaQueryWrapper);
        return Result.ok(order);
    }
}
